package net.bplaced.streetfighter.utils.update;

import net.bplaced.streetfighter.R;
import net.bplaced.streetfighter.lib.model.AppVersion;
import net.bplaced.streetfighter.lib.utils.RuntimeData;
import net.bplaced.streetfighter.lib.utils.RuntimeDataKey;
import android.app.DownloadManager;
import android.app.DownloadManager.Request;
import android.app.ListActivity;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

/**
 * @author Sebastian Hoffmann <bo.hoffi@googlemail.com>
 */
public class UpdateActivity
        extends ListActivity {
    public static int iconDrawableId = -1;

    private UpdateInfoAdapter adapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        this.setTitle("App Update");
        this.setContentView(R.layout.updates);

        AppVersion[] versions = null;
        if (RuntimeData.getInstance().get(RuntimeDataKey.UPDATES) != null) {

            versions = (AppVersion[]) RuntimeData.getInstance().get(RuntimeDataKey.UPDATES).getData();
        }
        this.adapter = new UpdateInfoAdapter(this, versions);
        this.getListView().setDivider(null);
        this.setListAdapter(this.adapter);
        this.configureView();
    }

    private void configureView() {

        if (UpdateActivity.iconDrawableId != -1) {
            final ImageView iconView = (ImageView) this.findViewById(R.id.icon_view);
            iconView.setImageDrawable(this.getResources().getDrawable(UpdateActivity.iconDrawableId));
        }

        final TextView versionLabel = (TextView) this.findViewById(R.id.version_label);
        versionLabel.setText("Version " + this.adapter.getLatestVersion().versionName);
    }

    public void onClickUpdate(View v) {

        this.startDownloadTask();
    }

    private void startDownloadTask() {

        final DownloadManager mgr = (DownloadManager) this.getSystemService(Context.DOWNLOAD_SERVICE);
        mgr.enqueue(new Request(Uri.parse(this.adapter.getLatestVersion().downloadLink)));
    }
}